/*
Copyright (c) 2008, Oleg S. Estekhin
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice,
      this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.
    * Neither the name of the copyright holders nor the names of its
      contributors may be used to endorse or promote products derived from this
      software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package ebml.viewer;

import java.io.File;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.concurrent.atomic.AtomicInteger;

import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;

import ebml.viewer.table.ExtendedColumn;
import ebml.viewer.table.ExtendedTableModel;
import ebml.viewer.table.FormatTableCellRenderer;

/** Contains a list of processed files. */
public final class FileListTableModel extends ExtendedTableModel {

    private static final ResourceBundle RESOURCES = ResourceBundle.getBundle(Resources.class.getName());

    private static final ExtendedColumn[] COLUMNS = {
            new ExtendedColumn("table.fileList.id", Integer.class, 50, null, null),
            new ExtendedColumn("table.fileList.file", File.class, 300, null, null),
            new ExtendedColumn("table.fileList.size", Long.class, 75, new FormatTableCellRenderer(NumberFormat.getIntegerInstance(), SwingConstants.RIGHT), null),
            new ExtendedColumn("table.fileList.status", String.class, 100, null, null),
    };


    private final List<Row> data;


    /** Creates a new <code>FileListTableModel</code> object. */
    public FileListTableModel() {
        super(COLUMNS);
        data = new ArrayList<Row>();
    }


    @Override
    public int getRowCount() {
        return data.size();
    }

    @Override
    public String getColumnName(int columnIndex) {
        return RESOURCES.getString(getColumnIdentifier(columnIndex));
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        Row row = data.get(rowIndex);
        switch (columnIndex) {
            case 0:
                return row.id;
            case 1:
                return row.file;
            case 2:
                return row.size;
            case 3:
                return row.status;
            default:
                throw new AssertionError(columnIndex);
        }
    }


    /**
     * Adds a file to the end of the list.
     *
     * @param file the file
     * @param status the initial file status
     *
     * @throws NullPointerException if <code>file</code> is <code>null</code>
     */
    public void addFile(final File file, final String status) {
        if (file == null) {
            throw new NullPointerException("file is null");
        }
        if (SwingUtilities.isEventDispatchThread()) {
            addFileUnsafe(file, status);
        } else {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    addFileUnsafe(file, status);
                }
            });
        }
    }

    private void addFileUnsafe(File file, String status) {
        int rowIndex = data.size();
        Row row = new Row(file, status);
        data.add(row);
        fireTableRowsInserted(rowIndex, rowIndex);
    }

    /**
     * Changes the file status.
     *
     * @param file the file
     * @param status the new file status
     *
     * @throws NullPointerException if <code>file</code> is <code>null</code>
     */
    public void setFileStatus(final File file, final String status) {
        if (file == null) {
            throw new NullPointerException("file is null");
        }
        if (SwingUtilities.isEventDispatchThread()) {
            setFileStatusUnsafe(file, status);
        } else {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    setFileStatusUnsafe(file, status);
                }
            });
        }
    }

    private void setFileStatusUnsafe(File file, String status) {
        int rowIndex = data.size() - 1;
        while (rowIndex >= 0 && !data.get(rowIndex).file.equals(file)) {
            rowIndex--;
        }
        if (rowIndex >= 0) {
            data.get(rowIndex).status = status;
            fireTableRowsUpdated(rowIndex, rowIndex);
        }
    }


    private static final class Row {

        private static final AtomicInteger ID = new AtomicInteger();

        private final int id;

        private final File file;

        private final long size;

        private String status;

        private Row(File file, String status) {
            id = ID.incrementAndGet();
            this.file = file;
            size = file.length();
            this.status = status;
        }

    }

}
